import { Node, AudioSource, AudioClip, resources, director } from 'cc';
import { GGResource } from './GGResource';

export class GGAudio {

    private static _audioSource: AudioSource;

    public static get audioSource() {
        return GGAudio._audioSource;
    }

    public static init() {
        let audioMgr = new Node();
        audioMgr.name = '__audioMgr__';

        //@en add to the scene.
        //@zh 添加节点到场景
        director.getScene().addChild(audioMgr);

        //@en make it as a persistent node, so it won't be destroied when scene change.
        //@zh 标记为常驻节点，这样场景切换的时候就不会被销毁了
        director.addPersistRootNode(audioMgr);

        //@en add AudioSource componrnt to play audios.
        //@zh 添加 AudioSource 组件，用于播放音频。
        GGAudio._audioSource = audioMgr.addComponent(AudioSource);
        GGAudio._audioSource.loop = true
    }

    /**
     * @en
     * play short audio, such as strikes,explosions
     * @zh
     * 播放短音频,比如 打击音效，爆炸音效等
     * @param sound clip or url for the audio
     * @param volume 
     */
    public static async playOneShot(sound: AudioClip | string, volume: number = 1.0) {
        if (sound instanceof AudioClip) {
            GGAudio._audioSource.playOneShot(sound, volume);
        } else {
            const clip: any = await GGResource.load(sound, AudioClip);
            return await GGAudio._audioSource.playOneShot(clip, volume);
        }
    }

    /**
     * @en
     * play long audio, such as the bg music
     * @zh
     * 播放长音频，比如 背景音乐
     * @param sound clip or url for the sound
     * @param volume 
     */
    public static async play(sound: AudioClip | string, volume: number = 1.0) {
        let clip;
        if (sound instanceof AudioClip) {
            clip = sound;
        } else {
            clip = await GGResource.load(sound, AudioClip);
        }

        GGAudio._audioSource.clip = clip;
        GGAudio._audioSource.play();
        GGAudio._audioSource.volume = 0.5;
    }

    /**
     * stop the audio play
     */
    public static stop() {
        GGAudio._audioSource.stop();
    }

    /**
     * pause the audio play
     */
    public static pause() {
        GGAudio._audioSource.pause();
    }

    /**
     * resume the audio play
     */
    public static resume() {
        GGAudio._audioSource.play();
    }
}

